package com.lottery.ruok.lottrey.fragment;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import org.greenrobot.eventbus.EventBus;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import utils.LogUtil;

abstract class LazyFragment extends BaseFragment {
    protected Activity mActivity;
    private View contentView;
    protected boolean mIsVisible;
    private Bundle bundle;
    private Unbinder unbinder;

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        mIsVisible = isVisibleToUser;
        if (mActivity != null) {
            lazyLoadData(bundle);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mActivity = (Activity) context;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,  Bundle savedInstanceState) {
        if (contentView != null) {
            ViewGroup parent = (ViewGroup) contentView.getParent();
            if (parent != null) {
                parent.removeView(contentView);
            }
        } else {
            contentView = inflater.inflate(setContentView(),
                    container, false);
        }

        bundle = getArguments();
        ButterKnife.bind(this, contentView);
        if (mIsVisible) {
            lazyLoadData(bundle);
        }
        EventBus.getDefault().register(this);
        unbinder = ButterKnife.bind(this, contentView);
        initView();
        return contentView;
    }

    protected abstract void initView();

    protected abstract int setContentView();

    protected abstract void lazyLoadData(Bundle bundle);

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        unbinder.unbind();
    }
}
